package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.util.UserThreadLocal;
import com.heima.media.dto.WmMaterialDto;
import com.heima.media.entity.WmMaterial;
import com.heima.media.mapper.WmMaterialMapper;
import com.heima.media.service.IWmMaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.minio.MinIOTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author gxm
 * @since 2023-12-18
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements IWmMaterialService {

    @Autowired
    private MinIOTemplate minIOTemplate;

    @Override
    public ResponseResult upload(MultipartFile file) {
        // 调用minio上传图片
        String url = minIOTemplate.upload(file);

        // 保存素材表
        WmMaterial material = new WmMaterial();
        material.setUserId(UserThreadLocal.get().getUserId());
        material.setUrl(url);
        material.setType(0);
        material.setIsCollection(false);
        material.setCreatedTime(new Date());
        this.save(material);
        return ResponseResult.okResult(material);
    }

    @Override
    public ResponseResult<WmMaterial> findList(WmMaterialDto dto) {
        //设置分页条件
        Page<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());

        //设置业务条件
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(dto.getIsCollection() != null, WmMaterial::getIsCollection, dto.getIsCollection());
        wrapper.eq(WmMaterial::getUserId, UserThreadLocal.get().getUserId());//当前登录人
        wrapper.orderByDesc(WmMaterial::getCreatedTime);//排序

        //执行查询
        this.page(page, wrapper);

        //返回
        return new PageResponseResult(dto.getPage(), dto.getSize(), page.getTotal(), page.getRecords());
    }
}
